<template>
  <div class="textarea-wrap">
    <template v-if="urlVisible">
      <div class="input-area" v-if="!btnLoading">
        <a-textarea
          placeholder="输入网址提取文案，仅支持抖音平台的视频"
          v-model:value="urlTxt"
          :autosize="{ maxRows: 3, minRows: 3 }"
          :bordered="false"
        ></a-textarea>
        <div class="input-btn-area">
          <a-button size="small" @click="closeUrlInput">取消</a-button>
          <a-button
            type="primary"
            size="small"
            @click="handleUrl(0, urlTxt)"
            :loading="btnLoading"
            >确定</a-button
          >
        </div>
      </div>
      <div class="loading-area" v-else>
        <div>提取成功，开始解析</div>
        <a-progress
          :stroke-color="{
            '0%': '#108ee9',
            '100%': '#87d068',
          }"
          :percent="100"
          :show-info="false"
        />
      </div>
    </template>
    <a-textarea
      v-if="!urlVisible"
      :bordered="false"
      v-model:value="text"
      :placeholder="placeholderTxt"
      show-count
      :maxlength="max_text_length"
      :autosize="{ maxRows: 8, minRows: 8 }"
    >
    </a-textarea>
    <div class="btn-box">
      <div class="btn-wrap" @click="showUrlInput">
        <span>AI生成</span>
      </div>
      <div class="btn-wrap" @click="openvideoExtr">
        <span class="text-active">从视频提取</span>
      </div>
    </div>

    <!-- <addAiCreate ref="AiCreateScriptRef"></addAiCreate> -->
  </div>
</template>
<script setup>
import { ref, watch, onBeforeUnmount } from "vue";
import { message, Modal } from "ant-design-vue";
import { useVModel } from "@vueuse/core";
import request from "@/common/utils/request";
import {max_text_length} from '@/common/utils/richTextProcessing.js'

const props = defineProps({
  value: String,

  extraID: {
    type: String,
    default: "",
  },
});

const emit = defineEmits(["update:value", "openAI", "openVideo", "chai_ing"]);
const text = useVModel(props, "value", emit);

let placeholderTxt = `您可以复制文案在此粘贴，AI深度学习，一键裂变。
您可以输入优质文案视频链接，A自动提取解析文案，深度学习，一键裂变。
您可以上传本地优质文案视频，AI自动提取解析文案，深学习，一键裂变。
50-500字最佳`;
let urlTxt = ref("");
let urlVisible = ref(false);
let btnLoading = ref(false);
let percent = ref(0);
const closeUrlInput = () => {
  urlVisible.value = false;
};
const showUrlInput = () => {
  emit("openAI");
};

const openvideoExtr = () => {
  emit("openVideo");
};

// 模拟上传进度
const getUploadProgress = () => {
  // if (percent.value < 30) {
  //   percent.value += 10;
  // } else if (percent.value >= 30 && percent.value < 90) {
  //   percent.value += 1;
  // } else if (percent.value >= 90 && percent.value < 98) {
  //   percent.value = (percent.value + 0.1).toFixed(1) - 0;
  // } else if (percent.value >= 98 && percent.value < 100) {
  //   percent.value = (percent.value + 0.01).toFixed(2) - 0;
  // } else {
  //   clearInterval(intervalId);
  // }
};
// 查询上传进度
const queryUploadProgress = (key) => {
  // timer.value = setInterval(() => {
  //   getUploadProgress();
  //   request
  //     .get("/work_ai", "/user/socialMedia/inspiration/extract/progress", {
  //       key,
  //     })
  //     .then((res) => {
  //       let { status, content } = res.result;
  //       if (status == 2) {
  //         text.value = content;
  //         clearInterval(timer.value);
  //         setTimeout(() => {
  //           percent.value = 0;
  //           btnLoading.value = false;
  //           urlVisible.value = false;
  //         }, 500);
  //       }
  //     })
  //     .catch((err) => {
  //       percent.value = 0;
  //       btnLoading.value = false;
  //       urlVisible.value = false;
  //       clearInterval(timer.value);
  //     });
  // }, 1000);
};
// 解析链接
const handleUrl = (video_source = 0, user_source) => {
  btnLoading.value = true;
  let params = {
    video_source, //0：抖音链接 1：本地视频链接
    user_source,
  };
  // request
  //   .post("/work_ai", "/user/socialMedia/inspiration/extract/video", params)
  //   .then((res) => {
  //     let { key, status, content } = res.result;
  //     getUploadProgress();
  //     if (status == 2) {
  //       text.value = content;
  //       clearInterval(timer.value);
  //     } else {
  //       queryUploadProgress(key);
  //     }
  //   })
  //   .finally(() => {
  //     setTimeout(() => {
  //       percent.value = 0;
  //       btnLoading.value = false;
  //       urlVisible.value = false;
  //       urlTxt.value = "";
  //     }, 500);
  //   });
};
const handleChange = ({ file, event }) => {
  urlVisible.value = true;
  btnLoading.value = true;
  if (file?.response?.msg == "OK") {
    let url = file.response.data.fileUrl;
    handleUrl(1, url);
  }
};

const pollInterval = ref(null);

const pollForStatus = (id) => {
  request
    .get("/work_ai", "/user/shotstack/video/conver/text/detail", {
      id: id,
    })
    .then((res) => {
      if (res.result.status == "2") {
        console.log(res.result.contents, "请求成功，状态为2");
        btnLoading.value = false;
        // 清除定时器
        urlVisible.value = false;

        let data = {
          contents: res.result.contents,
          source: "2",
        };

        emit("update", JSON.parse(JSON.stringify(data)));
        clearTimeout(pollInterval.value);
      } else if (res.result.status == "3") {
        message.error("提取失败，请检查输入或稍后重试");
        urlVisible.value = false;
        btnLoading.value = false;
        // 清除定时器
        clearTimeout(pollInterval.value);
      } else {
        console.log("状态不是2，继续轮询...");
        emit("chai_ing");
        // 设置下一次轮询
        pollInterval.value = setTimeout(() => pollForStatus(id), 3000); // 3秒后再次轮询
      }
    })
    .catch((error) => {
      console.error("请求失败:", error);
      // 错误处理逻辑
      btnLoading.value = false;
      // 清除定时器
      clearTimeout(pollInterval.value);
    });
};

watch(
  () => props.extraID,
  (newVal) => {
    if (!newVal) return;
    urlVisible.value = true;
    btnLoading.value = true;
    // 开始轮询
    pollForStatus(newVal);
  }
);

// 在组件卸载前清除定时器
onBeforeUnmount(() => {
  if (pollInterval.value) {
    clearTimeout(pollInterval.value);
  }
});
</script>
<style lang="less" scoped>
.textarea-wrap {
  display: flex;
  justify-content: space-between;
  flex-direction: column;
  background-color: #f5f5fc;
  border-radius: 5px;
  padding: 10px 10px 5px 10px;
  height: 260px;
  box-sizing: border-box;
}
.btn-box {
  display: flex;
  gap: 5px;
  justify-content: space-between;
  align-items: center;
  padding-top: 25px;
}
.btn-wrap {
  width: 50%;
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 5px;
  padding: 5px 20px;
  cursor: pointer;
  &:hover {
    color: var(--ss-primary-color);
    .text-active {
      color: var(--ss-primary-color);
    }
  }
  img {
    width: 20px;
    height: 20px;
    margin-right: 5px;
  }
}
.input-area {
  background-color: #fff;
  border-radius: 5px;
}
.input-btn-area {
  display: flex;
  justify-content: flex-end;
  gap: 5px;
  margin-top: 5px;
  padding: 5px;
}
.loading-area {
  background-color: #fff;
  padding: 20px;
  border-radius: 5px;
}
</style>
